#include"socket.hpp"
#include"protocal.hpp"

std::string execute(Protocal::Request& req)
{
    int x=req.GetX();
    int y=req.GetY();
    char oper=req.GetOper();
    Protocal::Response res(0,1);
    switch(oper)
    {
        case '+':res.SetResult(x+y);break;
        case '-':res.SetResult(x-y);break;
        case '*':res.SetResult(x*y);break;
        case '/':
        if(y==0)
            res.SetCode(0);
        else
            res.SetResult(x/y);
        break;
    }
    std::string response;
    res.Serialize(&response);
    return response;
}

int main()
{
    std::unique_ptr<Net_Work::TcpSocket> server=std::make_unique<Net_Work::TcpSocket>();
    server->BuildListenSocketMethod(8080,5);
    std::string ip;
    uint16_t port;
    std::unique_ptr<Net_Work::TcpSocket> comu((Net_Work::TcpSocket*)server->AcceptConnection(&ip,&port));//这里我们不关心对方的信息
    if(comu.get()==nullptr)
        return 0;
    std::string msg;
    while(true)
    {
        if(comu->Recv(&msg)==false)//获取到数据直接接在后面
        {
            break;
        }
        Protocal::Request req;
        if(req.DeSerialize(msg))
        {
            std::string response=execute(req);
            comu->Send(response);
            msg="";
        }
    }
}